package com.lagou.controller;/**
 * Created by IntelliJ IDEA.
 * User: Yangdx.
 * Date: 2020/7/26.
 * Time: 1:17.
 * Tags: Code, we are serious.
 */

import com.lagou.model.Token;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author
 * @create 2020-07-26 1:17
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Value("${config.cookie.name.auth}")
    private String cookieTag;

    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(HttpServletResponse response,
                            @PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code) {
        Token token = userService.register(email, password, code);
        if (token != null) {
            Cookie cookie = new Cookie(cookieTag,token.getToken());
            cookie.setPath("/");
            response.addCookie(cookie);
            return true;
        }
        return false;
    }

    @GetMapping("/isRegistered/{email}")
    public boolean checkRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response,
                        @PathVariable String email,
                        @PathVariable String password) {
        Token token = userService.login(email, password);
        if (token != null) {
            Cookie cookie = new Cookie(cookieTag,token.getToken());
            cookie.setPath("/");
            response.addCookie(cookie);
            return token.getEmail();
        }
        return "";
    }

    @GetMapping("/info/{token}")
    public String getEmailByToken(@PathVariable String token) {
        return userService.getEmailByToken(token);
    }

    @GetMapping("/logout")
    public void logout(HttpServletResponse response) {
        userService.logout();
        response.addHeader(cookieTag, "");
    }
}
